package com.anita.member.application.service;

import com.anita.member.application.command.MemberUpdateProfileCommand;
import com.anita.member.application.port.in.MemberUpdateProfileUseCase;
import com.anita.member.common.enums.Resp;
import com.anita.member.common.exception.BusinessException;
import com.anita.member.domain.model.member.*;
import com.anita.member.domain.repository.MemberRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author qiu
 * @date 2025/10/21
 * @description
 */
@Slf4j
@Service
@Transactional
public class MemberUpdateProfileService implements MemberUpdateProfileUseCase {

    @Resource
    private MemberRepository memberRepository;

    /**
     * 更新会员个人资料
     * @param command
     */
    @Override
    public void updateProfile(MemberUpdateProfileCommand command) {
        Optional<Member> memberOptional = memberRepository.findById(MemberId.of(command.id()));
        if(memberOptional.isEmpty()){
            throw new BusinessException(Resp.USER_NOT_FOUND);
        }

        Member member = memberOptional.get();

        //更新手机号
        if(command.phone() != null && !command.phone().equals(member.getPhone().value())){
            if(memberRepository.existsByPhone(Phone.of(command.phone()))){
                throw new BusinessException(Resp.USER_PHONE_ALREADY_EXISTS);
            }
            member.updatePhone(Phone.of(command.phone()));
        }

        //更新邮箱
        if(command.email() != null && !command.email().equals(member.getEmail().value())){
            if(memberRepository.existsByEmail(Email.of(command.email()))){
                throw new BusinessException(Resp.USER_EMAIL_ALREADY_EXISTS);
            }
            member.updateEmail(Email.of(command.email()));
        }

        //保存更新
        memberRepository.save(member);

        log.info("会员更新个人资料成功: {}", member.getUserName().value());
    }
}
